package edu.gatech.oad.publicstaticdroidmain.taskmanager.ui;

import java.util.Calendar;
import java.util.Date;

import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Database;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.TaskManager;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task.Recurrence;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.TaskManagerDBFacade;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * An Android activity that enables a user to create a a new task  
 * 
 * 
 * @version 1.0 Feb 22 2012
 * @author Daniel Hull
 */
public class NewTaskActivity extends AbstractTaskManagerActivity {
	
        private static final Recurrence[] RECURRENCES = {
        	Task.Recurrence.ONCE, 
        	Task.Recurrence.DAILY, 
        	Task.Recurrence.WEEKLY, 
        	Task.Recurrence.MONTHLY, 
        	Task.Recurrence.YEARLY
        };
        
        private static final String[] RECURRENCE_STRINGS = {
        	"Once",
        	"Daily",
        	"Weekly",
        	"Monthly",
        	"Yearly"
        };
    
	private TaskManagerDBFacade facade;
	
	private TextView nameField;
	private TextView descriptionField;
	private Button date;
		private int year;
		private int month;
		private int day;
	private Button time;
		private int hour;
		private int minute;
	private Button add;
	private TextView addressField;
	private Button customAddress;
	
	private Spinner categorySpinner;
	private Spinner recurrenceSpinner;
	
	private final int DATE_DIALOG_ID = 0;
	private final int TIME_DIALOG_ID = 1;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_task);
		facade = ((TaskManagerApplication)(getApplication())).getFacade();
		Task t = null;
		Bundle b = this.getIntent().getExtras();
		if(b!=null) {
		    t = (Task) b.getSerializable("task");
		}
		
		nameField = (TextView) findViewById(R.id.name);
		descriptionField = (TextView) findViewById(R.id.description);
		date = (Button) findViewById(R.id.date);
		time = (Button) findViewById(R.id.time);
		addressField = (TextView) findViewById(R.id.address);
		customAddress = (Button) findViewById(R.id.custom_address);
		add = (Button) findViewById(R.id.add);
		
		categorySpinner = (Spinner) findViewById(R.id.taskAddCategorySpinner);
		setUpCategorySpinner();
		
		recurrenceSpinner = (Spinner) findViewById(R.id.taskAddRecurrenceSpinner);
		setUpRecurrenceSpinner();
		
		 // add a click listener to the button
		OnClickListener buttonListener = new NewTaskActivityButtonListener();
        date.setOnClickListener(buttonListener);
        time.setOnClickListener(buttonListener);
        add.setOnClickListener(buttonListener);
        
//        if(t == null) {
        	final Calendar calendar = Calendar.getInstance();
        	year = calendar.get(Calendar.YEAR);
        	month = calendar.get(Calendar.MONTH);
        	day = calendar.get(Calendar.DAY_OF_MONTH);
        	hour = calendar.get(Calendar.HOUR_OF_DAY);
        	minute = calendar.get(Calendar.MINUTE);
//        } else {
//        	Date d = t.getDueDate();
//        	d.getYear();
//        	year = d.getYear(); 
//        	month = d.getMonth();
//        	day = d.getDay();
//        	hour = d.getHours();
//        	minute = d.getMinutes();
//        	date.setText(month + "-" + day + "-" + year);
//        	time.setText(hour + ":" + minute);
//        	
//        	nameField.setText(t.getName());
//        	descriptionField.setText(t.getDescription());
//        	addressField.setText(t.getName());
//        }
        
        
	}

	/**
	 * sets up a spinner with categories as choices
	 */
	private void setUpCategorySpinner() {
	    ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, 
		    android.R.layout.simple_spinner_item, 
		    facade.getCategories());
	    categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    categorySpinner.setAdapter(categoryAdapter);
	}
	
	/**
	 * sets up a spinner with recurrence options as choices
	 */
	private void setUpRecurrenceSpinner() {
	    ArrayAdapter<String> recurrenceAdapter = new ArrayAdapter<String>(this, 
		    android.R.layout.simple_spinner_item, 
		    RECURRENCE_STRINGS);
	    recurrenceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    recurrenceSpinner.setAdapter(recurrenceAdapter);
	}

	/**
	 * creates a date option
	 */
	private DatePickerDialog.OnDateSetListener dateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int syear, int monthOfYear, int dayOfMonth) {
                    year = syear;
                    month = monthOfYear;
                    day = dayOfMonth;
                    updateDateDisplay();
                }
            };
            
    /**
     * creates a time option
     */
    private TimePickerDialog.OnTimeSetListener timeSetListener =
    		new TimePickerDialog.OnTimeSetListener() {
    	
    			public void onTimeSet(TimePicker view, int hourOfDay, int sminute) {
    				hour = hourOfDay;
    				minute = sminute;
    				updateTimeDisplay();
    			}
            };
            
    /**
     * updates the date shown on the Dialog the activity
     */
    private void updateDateDisplay() {
    	date.setText(
    			new StringBuilder()
                            // Month is 0 based so add 1
    			.append(month + 1).append("-")
    			.append(day).append("-")
    			.append(year).append(" "));
    }
    
    /**
     * updates the time shown on the Time Dialog the activity
     */
    private void updateTimeDisplay() {
        time.setText(
            new StringBuilder()
                    .append(pad(hour)).append(":")
                    .append(pad(minute)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
            
    @Override
    protected Dialog onCreateDialog(int id) {
    	switch (id) {
    	case DATE_DIALOG_ID:
    		return new DatePickerDialog(this, dateSetListener, year, month, day);
    	case TIME_DIALOG_ID:
    		return new TimePickerDialog(this, timeSetListener, hour, minute, false);
    	}
    	return null;
    }
    
    /**
     * Private class for the add button listener
     * 
     * @author Daniel Hull
     *
     */
    private class NewTaskActivityButtonListener implements OnClickListener {

    	/**
    	 * when ADD is clicked adds a task through the TaskManager class
    	 */
    	public void onClick(View view) {

    		switch(view.getId()) {
    		case R.id.date:
    			showDialog(DATE_DIALOG_ID);
    			break;
    		case R.id.time:
    			showDialog(TIME_DIALOG_ID);
    			break;
    		case R.id.add:
    		    	String name = nameField.getText().toString();
    		    	String description = descriptionField.getText().toString();
    		    	
    		    	Date dueDate = new Date();
    		    	dueDate.setYear(year);
    		    	dueDate.setMonth(month);
    		    	dueDate.setDate(day);
    		    	dueDate.setHours(hour);
    		    	dueDate.setMinutes(minute);
    		    	
    		    	double latitude = 19.92;
    		    	double longitude = 02.15;
    		    	Task.Recurrence recurrence = RECURRENCES[recurrenceSpinner.getSelectedItemPosition()];
    		    	String category = facade.getCategories()[categorySpinner.getSelectedItemPosition()];
    		    	
    		    	facade.addTask(name, description, dueDate, latitude, longitude, recurrence, category);

    			startUIActivity(getString(R.string.activity_task_view));
    			
    			break;
    		}
					
    	}
            	
    }
            

}
